import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import {
  CarouselAdminCreateDto,
  CarouselAdminIndexDto,
  CarouselAdminUpdateDto, CarouselAllDto,
} from './carousel.dto';
import { CarouselModel } from './carousel.model';
import { omitUndefined } from "@/common/utils/utils";
import { BooleanNumber } from "common/utils/data";

@Injectable()
export class CarouselService {
  constructor(
    @InjectRepository(CarouselModel)
    private readonly carouselModelRepository: Repository<CarouselModel>,
  ) {}

  async all(param: CarouselAllDto): Promise<CarouselModel[]> {
    return this.carouselModelRepository.find({
      where: {
        status: BooleanNumber.true,
        positionCode: param.positionCode,
      },
      select: ['uuid', 'img', 'url','title','desc', 'mobileJumpType', 'mobileJumpId', 'mobileJumpExtra'],
      order: {
        sort: 'ASC',
        id: 'DESC',
      },
    });
  }

  async adminIndex(query: CarouselAdminIndexDto) {
    interface IFilter {
      title?: any;
      status?: any;
      positionCode?: any;
    }
    const filter: IFilter = {};

    if (query.title) {
      filter.title = Like(`%${query.title}%`);
    }

    if (query.status) {
      filter.status = query.status;
    }

    if (query.positionCode) {
      filter.positionCode = query.positionCode;
    }

    return this.carouselModelRepository.findAndCount({
      where: filter,
      skip: query.getOffset(),
      take: query.getPageSize(),
      select: [
        'id',
        'uuid',
        'title',
        'img',
        'url',
        'sort',
        'status',
        'desc',
        'mobileJumpType',
        'mobileJumpId',
        'mobileJumpExtra',
        'positionCode',
        'createTime',
        'updateTime',
      ],
      order: {
        status: 'DESC',
        sort: 'ASC',
        id: 'DESC',
      },
    });
  }

  async adminCreate(body: CarouselAdminCreateDto): Promise<void> {
    await this.carouselModelRepository.save({
      ...body,
    });
  }

  async adminUpdate(body: CarouselAdminUpdateDto, uuid: string): Promise<void> {
    await this.carouselModelRepository.update(
      {
        uuid,
      },
      omitUndefined(body),
    );
  }

  async adminDestroy(uuid: string): Promise<void> {
    await this.carouselModelRepository.delete({
      uuid,
    });
  }
}
